const exec = require('child_process').exec
const iconv = require('iconv-lite')

function cmdExec (cmd, isPrint = true) {
  const encoding = 'cp936'
  const binaryEncoding = 'binary'
  return new Promise(function (resolve, reject) {
    let resStr = ''
    const build = exec(cmd, {encoding: binaryEncoding})
    build.stdout.on('data', (data) => {
      let str = iconv.decode(Buffer.from(data, binaryEncoding), encoding)
      resStr += str
      isPrint && console.log(str)
    })
    build.stderr.on('data', (error) => {
      let str = iconv.decode(Buffer.from(error, binaryEncoding), encoding)
      resStr += str
      isPrint && console.error(str)
    })
    build.on('close', () => {
      // console.log('CMD close  close')
      resolve(resStr)
    })
    build.on('exit', () => {
      // console.log('CMD exit  exit')
      resolve(resStr)
    })
  })
}

module.exports = {cmdExec}
